package wnhz.com.business.shareshop.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.netcallback.StringDialogCallback;
import wnhz.com.business.rebateshop.activity.home.ShareFriandActivity;
import wnhz.com.business.shareshop.activity.home.RebateGoodsDetailsActivityS;
import wnhz.com.business.shareshop.bean.ShopFollowBean;
import wnhz.com.business.shareshop.bean.ShopListInfoBean;
import wnhz.com.business.shareshop.bean.StoreShopBean;
import wnhz.com.business.uitls.GsonUtil;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * 共享商城店铺界面
 */
public class StoreActivityS extends BaseActivity implements View.OnClickListener, ActionBarClickListener, OnRefreshLoadmoreListener {

    @BindView(R.id.ll_store)
    LinearLayout llStore;
    @BindView(R.id.tv_call)
    TextView tvCall;
    @BindView(R.id.tv_fansi)
    TextView tvFansi;
    @BindView(R.id.tv_allnumber)
    TextView tvAllnumber;
    @BindView(R.id.tv_paixu)
    TextView tvPaixu;
    @BindView(R.id.recycler_storedata)
    RecyclerView recyclerStoredata;
    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;
    @BindView(R.id.store_name)
    TextView storeName;
    @BindView(R.id.store_describe)
    TextView storeDescribe;
    @BindView(R.id.store_img)
    ImageView storeImg;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.tv_msg)
    TextView tvMsg;
    @BindView(R.id.empty_layout)
    LinearLayout emptyLayout;

    private String title = "";
    private String Status = "";
    private PopupWindow pop;
    private LinearLayout ll_boss, ll_1, ll_2, ll_3, ll_4, ll_5;
    private TextView tv_1, tv_2, tv_3, tv_4, tv_5;
    private ImageView img_1, img_2, img_3, img_4, img_5;
    private List<String> urllist = new ArrayList<>();
    private BaseRVAdapter adapter;
    private String store_id;

    private String sort = "1";
    private View contentView;
    private boolean b;
    private int page = 0;
    private StoreShopBean storeShopBean = new StoreShopBean();
    private List<ShopListInfoBean.InfoBean> shopList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stores);
        ButterKnife.bind(this);
        parseIntent();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        initSmartRefreshLayout();
    }

    private void initSmartRefreshLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
    }

    public static Intent createIntent(Context context, String store_id) {
        Intent intent = new Intent(context, StoreActivityS.class);
        intent.putExtra("store_id", store_id);
        return intent;
    }

    private void parseIntent() {
        Intent intent = getIntent();
        store_id = intent.getStringExtra("store_id");
        getShopDataInfo();
        getShopLists(sort);
    }


    //猜你喜欢图片列表地址
    private void initTestGallylist(List<ShopListInfoBean.InfoBean> shopListInfoBean) {
        tvAllnumber.setText(shopListInfoBean.size() + "");
        recyclerStoredata.setLayoutManager(new GridLayoutManager(StoreActivityS.this, 2, GridLayoutManager.VERTICAL, false));
        urllist.clear();
        for (int i = 0; i < shopListInfoBean.size(); i++) {
            urllist.add(shopListInfoBean.get(i).getLogo_pic());
        }
        initList(shopListInfoBean);
    }


    /*
   *底部商品列表
   */
    private void initList(final List<ShopListInfoBean.InfoBean> shopListInfoBean) {
        adapter = new BaseRVAdapter(StoreActivityS.this, urllist) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_rebatehome_bootlist;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                holder.setTextView(R.id.item_tv_rebatehome_name, shopListInfoBean.get(position).getGoods_name());
                holder.setTextView(R.id.item_tv_rebatehome_info, "模拟简介简介简介简介简介");
                holder.setTextView(R.id.item_tv_rebatehome_price, "¥" + shopListInfoBean.get(position).getPrice());
                Glide.with(StoreActivityS.this).load(shopListInfoBean.get(position).getLogo_pic()).into(holder.getImageView(R.id.item_img_rebatehome));

                holder.getView(R.id.item_tv_rebatehome_share).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转分享页面  (页面标题: 分享商品给好友)
                        startActivity(ShareFriandActivity.createIntent(StoreActivityS.this));
                    }
                });
            }
        };

        adapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                startActivity(RebateGoodsDetailsActivityS.createIntent(StoreActivityS.this, shopListInfoBean.get(position).getGoods_id(), shopListInfoBean.get(position).getLogo_pic(), "4"));
            }
        });
        recyclerStoredata.setAdapter(adapter);
    }


    @OnClick({R.id.ll_store, R.id.tv_call, R.id.tv_paixu, R.id.iv_actionbar_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //商家中心
            case R.id.ll_store:
                startActivity(MerchatCenterActivityS.createIntent(this));
                break;
            case R.id.tv_call://客服
                break;
            case R.id.tv_paixu://商品排序
                makepop();
                break;
            case R.id.iv_actionbar_left://回退
                finish();
                break;
        }
    }


    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {
        if (b) {
            addFollow("2");//取消关注
        } else {
            addFollow("1");//去关注
        }
    }

/*    *//**/

    /**
     * 关注与取消关注店铺
     */

    private void addFollow(String type) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("store_id", store_id);
        map.put("goods_type", "4");
        map.put("type", type);
        XUtil.Post(Url.STORE_FOLLOWSTORE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("wxf", "店铺关注" + result);
                if (b) {
                    b = false;
                    actionbar.setData(title, R.drawable.ic_lefft_white, null, R.drawable.ic_dianpu_guanzhu, "关注", 0, StoreActivityS.this);
                } else {
                    b = true;
                    actionbar.setData(title, R.drawable.ic_lefft_white, null, R.drawable.ic_dianpu_guanzhu, "已关注", 0, StoreActivityS.this);
                }
                ShopFollowBean shopFollowBean = GsonUtil.parseJsonToBean(result, ShopFollowBean.class);
                ToastUtils.showToast(MyApplication.getInstance().getApplicationContext(), shopFollowBean.getInfo());
            }
        });
    }

    @Override
    public void onEditTextClick() {

    }

    //排序pop
    private void makepop() {
        if (pop == null || contentView == null) {
            contentView = LayoutInflater.from(this).inflate(R.layout.item_pop_paixu, null);
            pop = new PopupWindow(contentView);
            pop.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            pop.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
            pop.setOutsideTouchable(true);
        }
        pop.showAsDropDown(actionbar, 0, 0, Gravity.NO_GRAVITY);
        ll_boss = (LinearLayout) contentView.findViewById(R.id.ll_boss);
        ll_1 = (LinearLayout) contentView.findViewById(R.id.ll_1);
        ll_2 = (LinearLayout) contentView.findViewById(R.id.ll_2);
        ll_3 = (LinearLayout) contentView.findViewById(R.id.ll_3);
        ll_4 = (LinearLayout) contentView.findViewById(R.id.ll_4);
        ll_5 = (LinearLayout) contentView.findViewById(R.id.ll_5);
        ll_1.setOnClickListener(this);
        ll_2.setOnClickListener(this);
        ll_3.setOnClickListener(this);
        ll_4.setOnClickListener(this);
        ll_5.setOnClickListener(this);
        ll_boss.setOnClickListener(this);

        tv_1 = (TextView) contentView.findViewById(R.id.tv_1);
        tv_2 = (TextView) contentView.findViewById(R.id.tv_2);
        tv_3 = (TextView) contentView.findViewById(R.id.tv_3);
        tv_4 = (TextView) contentView.findViewById(R.id.tv_4);
        tv_5 = (TextView) contentView.findViewById(R.id.tv_5);

        img_1 = (ImageView) contentView.findViewById(R.id.img_1);
        img_2 = (ImageView) contentView.findViewById(R.id.img_2);
        img_3 = (ImageView) contentView.findViewById(R.id.img_3);
        img_4 = (ImageView) contentView.findViewById(R.id.img_4);
        img_5 = (ImageView) contentView.findViewById(R.id.img_5);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_boss:
                pop.dismiss();
                break;
            case R.id.ll_1:
                tv_1.setTextColor(getResources().getColor(R.color.red255));
                tv_2.setTextColor(getResources().getColor(R.color.text51));
                tv_3.setTextColor(getResources().getColor(R.color.text51));
                tv_4.setTextColor(getResources().getColor(R.color.text51));
                tv_5.setTextColor(getResources().getColor(R.color.text51));
                img_1.setVisibility(View.VISIBLE);
                img_2.setVisibility(View.GONE);
                img_3.setVisibility(View.GONE);
                img_4.setVisibility(View.GONE);
                img_5.setVisibility(View.GONE);
                tvPaixu.setText(tv_1.getText().toString());
                pop.dismiss();
                sort = "1";
                break;
            case R.id.ll_2:
                tv_1.setTextColor(getResources().getColor(R.color.text51));
                tv_2.setTextColor(getResources().getColor(R.color.red255));
                tv_3.setTextColor(getResources().getColor(R.color.text51));
                tv_4.setTextColor(getResources().getColor(R.color.text51));
                tv_5.setTextColor(getResources().getColor(R.color.text51));
                img_1.setVisibility(View.GONE);
                img_2.setVisibility(View.VISIBLE);
                img_3.setVisibility(View.GONE);
                img_4.setVisibility(View.GONE);
                img_5.setVisibility(View.GONE);
                tvPaixu.setText(tv_2.getText().toString());
                pop.dismiss();
                sort = "2";
                break;
            case R.id.ll_3:
                tv_1.setTextColor(getResources().getColor(R.color.text51));
                tv_2.setTextColor(getResources().getColor(R.color.text51));
                tv_3.setTextColor(getResources().getColor(R.color.red255));
                tv_4.setTextColor(getResources().getColor(R.color.text51));
                tv_5.setTextColor(getResources().getColor(R.color.text51));
                img_1.setVisibility(View.GONE);
                img_2.setVisibility(View.GONE);
                img_3.setVisibility(View.VISIBLE);
                img_4.setVisibility(View.GONE);
                img_5.setVisibility(View.GONE);
                tvPaixu.setText(tv_3.getText().toString());
                pop.dismiss();
                sort = "3";
                break;
            case R.id.ll_4:
                tv_1.setTextColor(getResources().getColor(R.color.text51));
                tv_2.setTextColor(getResources().getColor(R.color.text51));
                tv_3.setTextColor(getResources().getColor(R.color.text51));
                tv_4.setTextColor(getResources().getColor(R.color.red255));
                tv_5.setTextColor(getResources().getColor(R.color.text51));
                img_1.setVisibility(View.GONE);
                img_2.setVisibility(View.GONE);
                img_3.setVisibility(View.GONE);
                img_4.setVisibility(View.VISIBLE);
                img_5.setVisibility(View.GONE);
                tvPaixu.setText(tv_4.getText().toString());
                pop.dismiss();
                sort = "4";
                break;
            case R.id.ll_5:
                tv_1.setTextColor(getResources().getColor(R.color.text51));
                tv_2.setTextColor(getResources().getColor(R.color.text51));
                tv_3.setTextColor(getResources().getColor(R.color.text51));
                tv_4.setTextColor(getResources().getColor(R.color.text51));
                tv_5.setTextColor(getResources().getColor(R.color.red255));
                img_1.setVisibility(View.GONE);
                img_2.setVisibility(View.GONE);
                img_3.setVisibility(View.GONE);
                img_4.setVisibility(View.GONE);
                img_5.setVisibility(View.VISIBLE);
                tvPaixu.setText(tv_5.getText().toString());
                pop.dismiss();
                sort = "5";
                break;
        }
        getShopLists(sort);
    }

    /**
     * 店铺信息
     */
    public void getShopDataInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("store_id", store_id);
        map.put("goods_type", "4");//1.拼团  2.返利  3.免费    4：共享商城
        OkGo.<String>post(Url.SHOP_INFO).tag(this).params(map, false).execute(new StringDialogCallback(this) {
            @Override
            public void onSuccess(Response<String> response) {
                LogUtils.e("wxf", "共享商城店铺详情" + response.body().toString());
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response.body());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String re = jsonObject.optString("re");
                if ("1".equals(re)) {
                    storeShopBean = GsonUtil.parseJsonToBean(response.body().toString(), StoreShopBean.class);
                    setBar(storeShopBean);
                } else if ("-1".equals(jsonObject.optString("re"))) {
                    MyToast(getResources().getString(R.string.login_out));
                    MyApplication.getInstance().gotoLoginActivity();
                } else {
                    MyToast(jsonObject.optString("info"));
                }
            }
        });
    }

    private void setBar(StoreShopBean storeShopBean) {
        String right = "";
        if (storeShopBean.getInfo().getStatus().equals("0")) {
            b = false;
            right = "关注";
        } else {
            b = true;
            right = "已关注";
        }
        if (TextUtils.isEmpty(title)) {
            title = "店铺";
        } else {
            title = storeShopBean.getInfo().getTitle();
        }
        storeName.setText(storeShopBean.getInfo().getName());
        storeDescribe.setText(storeShopBean.getInfo().getTitle());
        Glide.with(this).load(storeShopBean.getInfo().getLogo()).dontAnimate().into(storeImg);
        tvFansi.setText(storeShopBean.getInfo().getNum());
        actionbar.setData(title, R.drawable.ic_lefft_white, null, R.drawable.ic_dianpu_guanzhu, right, 0, this);
    }

    /**
     * 店铺的所有商品
     */
    public void getShopLists(String sort) {
        Map<String, String> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("store_id", store_id);
        map.put("goods_type", "4"); //1.拼团  2.返利  3.免费    4：共享商城
        map.put("sort", sort);//排序   1-默认  2-销量  3-最新上架  4-价格倒序  5-价格顺序
        map.put("page", page + "");
        OkGo.<String>post(Url.SHOP_LISTS).tag(this).params(map, false).execute(new StringDialogCallback(this) {
            @Override
            public void onSuccess(Response<String> response) {
                LogUtils.e("wxf", "店铺所有商品列表" + response.body().toString());
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response.body());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String re = jsonObject.optString("re");
                if ("1".equals(re)) {
                    ShopListInfoBean shopListInfoBean = GsonUtil.parseJsonToBean(response.body().toString(), ShopListInfoBean.class);
                    if (shopListInfoBean.getInfo() != null) {
                        initTestGallylist(shopListInfoBean.getInfo());
                    }
                    if (page == 0) {
                        if (null != shopList) {
                            shopList.clear();
                        }
                        shopList.addAll(shopListInfoBean.getInfo());

                        mRefreshLayout.finishRefresh();
                        mRefreshLayout.resetNoMoreData();
                    } else {
                        mRefreshLayout.finishLoadmore();
                        adapter.notifyDataSetChanged();
                    }
                    initTestGallylist(shopListInfoBean.getInfo());

                } else if ("-1".equals(jsonObject.optString("re"))) {
                    //这里是没有数据
                    MyToast(getResources().getString(R.string.login_out));
                    MyApplication.getInstance().gotoLoginActivity();
                } else {
                    MyToast(jsonObject.optString("info"));
                    if (page == 0) {
                        mRefreshLayout.setVisibility(View.GONE);
                        emptyLayout.setVisibility(View.VISIBLE);
                        tvMsg.setText("暂无商品");
                    } else {
                        mRefreshLayout.finishLoadmore();
                        mRefreshLayout.finishLoadmoreWithNoMoreData();//将不会再次触发加载更多事件
                        emptyLayout.setVisibility(View.GONE);
                    }
                }
            }
        });

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                page = page + 1;
                getShopLists(sort);
            }
        },1000);

    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {

        mRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 0;
                getShopLists(sort);
            }
        },1000);
    }
}
